import 'package:flutter/material.dart';
import 'package:flutter_baselib/lib.dart';
import 'package:flutter_baselib_example/config/login_info_manager.dart';
import 'package:flutter_baselib_example/module/login/model/login_result_bean.dart';
import 'package:flutter_baselib_example/module/userlist/model/user_detail_bean.dart';
import 'package:flutter_baselib_example/net/http_urls.dart';

///@date:  2021/3/1 11:57
///@author:  lixu
///@description: 登录ViewModel
class LoginViewModel extends BaseCommonViewModel {
  ///登录响应对象
  LoginResultBean _loginResultBean;

  CancelToken loginCancelToken;

  LoginResultBean get loginResultBean => _loginResultBean;

  @override
  String getTag() {
    return 'LoginViewModel';
  }

  ///登录
  Future<bool> onLogin(BuildContext context) async {
    if (isLoading) {
      return null;
    }

    Map<String, dynamic> map = {
      'account': '15015001500',
      'pass': '123qwe',
      'appType': 'PATIENT',
      'device': 'ANDROID',
      'push': '13065ffa4e22e63efd2',
    };

    loginCancelToken = CancelToken();
    await api.request<LoginResultBean>(
      HttpUrls.loginUrl,
      params: map,
      cancelToken: loginCancelToken,
      loadingText: '正在登录...',
      isCancelableDialog: true,
      onSuccess: (LoginResultBean bean) {
        _loginResultBean = bean;
        ToastUtils.show('登录成功');
      },
      onError: (HttpErrorBean errorBean) {
        _loginResultBean = null;
        LogUtils.e(getTag(), '登录失败');
      },
    );
    update();
    return _loginResultBean?.token != null && _loginResultBean?.user != null;
  }

  ///TODO 此处只是为了演示http获取List对象
  ///获取用户列表
  Future<List<UserDetailBean>> getUserList(BuildContext context) async {
    if (_loginResultBean == null) {
      ///先登录获取token添加到请求头
      await onLogin(context);
    }

    var params = {
      'userId': loginInfo.userBean?.userId,
      'token': loginInfo.token,
    };

    List<UserDetailBean> userList;
    await api.requestList<UserDetailBean>(
      HttpUrls.userListUrl,
      params: params,
      loadingText: '加载中...',
      isCancelableDialog: false,
      onSuccess: (List<UserDetailBean> list) {
        userList = list;
        ToastUtils.show('获取用户列表成功，用户数：${list?.length}');
      },
      onError: (HttpErrorBean errorBean) {
        LogUtils.e(getTag(), '获取用户列表失败');
      },
    );

    return userList;
  }

  @override
  void dispose() {
    super.dispose();

    ///页面关闭时，取消http请求
    api.cancel(loginCancelToken);
  }
}
